
/**
 * Date:2019年6月4日上午11:29:48
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.client.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Queue;
import java.util.stream.Collectors;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import com.xue.im.client.core.IMClientContext;
import com.xue.im.common.IMUtil;
import com.xue.im.common.IMUtil.MessageType;
import com.xue.im.common.vo.Message;
import com.xue.im.common.vo.User;

import io.netty.util.internal.StringUtil;

public class ChatDialog extends JFrame {
	private static final long serialVersionUID = 1L;

	private static final ChatDialog instance = new ChatDialog();
	private JTextArea taMsgList;// 消息列表文本框

	// private JEditorPane taMsgList;//
	private JScrollBar scrollBarMsg;// 消息滚动条
	// private String receiver = IMUtil.ALL;
	private JLabel lbUsername;// 用户姓名
	private JLabel lbImage;
	private User otherUser;// 对方用户
	private JTextArea taMsg;// 消息内容

	private boolean isSendFile = false;

	public static ChatDialog getInstance() {
		return instance;
	}

	/**
	 * Create the frame.
	 */
	public ChatDialog() {
		//setResizable(false);
		setIconImage(IMClientContext.client.getImage());
		setBounds(100, 100, 700, 600);
		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(5, 5));

		lbImage = new JLabel(IMClientContext.man);

		lbImage.setBorder(new LineBorder(new Color(0, 0, 0)));
		lbImage.setPreferredSize(new Dimension(64, 64));
		panel.add(lbImage, BorderLayout.WEST);

		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));

		lbUsername = new JLabel();
		lbUsername.setFont(new Font("Dialog", Font.BOLD, 14));
		panel_1.add(lbUsername, BorderLayout.CENTER);

		JLabel lblNewLabel_2 = new JLabel("...");
		panel_1.add(lblNewLabel_2, BorderLayout.SOUTH);

		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.9);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		contentPane.add(splitPane, BorderLayout.CENTER);

		JPanel panel_2 = new JPanel();
		panel_2.setToolTipText("panel_2");
		splitPane.setRightComponent(panel_2);
		panel_2.setLayout(new BorderLayout(0, 0));

		JPanel panel_3 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_3.getLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		panel_2.add(panel_3, BorderLayout.NORTH);

		JButton btFont = new JButton("字体");
		btFont.setEnabled(false);
		panel_3.add(btFont);

		JButton btnNewButton = new JButton("震屏");
		btnNewButton.setEnabled(false);
		panel_3.add(btnNewButton);

		JPanel panel_4 = new JPanel();
		panel_2.add(panel_4, BorderLayout.CENTER);
		panel_4.setLayout(new BorderLayout(0, 0));

		JPanel panel_5 = new JPanel();
		panel_4.add(panel_5, BorderLayout.EAST);
		panel_5.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JButton btSend = new JButton("发 送");
		btSend.setPreferredSize(new Dimension(124, 100));
		panel_5.add(btSend);

		JPanel panel_6 = new JPanel();
		panel_4.add(panel_6, BorderLayout.CENTER);
		panel_6.setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane_1 = new JScrollPane();
		panel_6.add(scrollPane_1, BorderLayout.CENTER);

		taMsg = new JTextArea();
		taMsg.setLineWrap(true);
		scrollPane_1.setViewportView(taMsg);
		bindEvent();

		JScrollPane scrollPaneMsg = new JScrollPane();

		taMsgList = new JTextArea();
		// taMsgList = new JEditorPane();
		// taMsgList.setContentType("text/html");
		// taMsgList.setEditable(false);
		// taMsgList.setLineWrap(true);

		scrollPaneMsg.setViewportView(taMsgList);
		scrollBarMsg = scrollPaneMsg.getVerticalScrollBar();

		splitPane.setLeftComponent(scrollPaneMsg);

		// 发送事件
		btSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				sendMessage();
			}
		});

	}

	private void bindEvent() {
		// 按ctr+enter换行

		taMsg.registerKeyboardAction(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				taMsg.setText(taMsg.getText() + "\n");
			}
		}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK),
				JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

		// 按enter发送
		taMsg.addKeyListener(new KeyListener() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (!e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER) {
					sendMessage();
				}
			}

			@Override
			public void keyReleased(KeyEvent e) {
			}

			@Override
			public void keyTyped(KeyEvent e) {
			}
		});

		taMsg.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (isSendFile) {
					taMsg.setText("");
					taMsg.setEditable(true);
					isSendFile = false;
				}
			}
		});

		// 绑定拖动文件
		taMsg.setTransferHandler(new TransferHandler() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean importData(JComponent comp, Transferable t) {
				DataFlavor df = t.getTransferDataFlavors()[0];
				try {
					if (df.isFlavorJavaFileListType()) {
						Object o = t.getTransferData(DataFlavor.javaFileListFlavor);
						String filepath = o.toString();
						if (filepath.startsWith("[")) {
							filepath = filepath.substring(1);
						}
						if (filepath.endsWith("]")) {
							filepath = filepath.substring(0, filepath.length() - 1);
						}
						filepath = filepath.split(",")[0];
						System.out.println(filepath);
						File f = new File(filepath);
						if (!f.isDirectory()) {// 不能是目录
							taMsg.setText(filepath);// 只获取第一项
							taMsg.setEditable(false);// 设置不可编辑
							isSendFile = true;
						}
						return true;
					} else {
						Object o = t.getTransferData(DataFlavor.stringFlavor);
						taMsg.setText(o.toString());
						return true;
					}
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}

			}

			@Override
			public boolean canImport(JComponent comp, DataFlavor[] flavors) {
				for (int i = 0; i < flavors.length; i++) {
					if (DataFlavor.javaFileListFlavor.equals(flavors[i])
							|| DataFlavor.stringFlavor.equals(flavors[i])) {
						return true;
					}
				}
				return false;
			}
		});

	}

	private void sendMessage() {
		String msg = taMsg.getText();
		if (isSendFile) {// 如果发送文件

			try {
				File file = new File(msg);
				byte[] fb = IMUtil.toByteArray(file);
				if (fb.length > IMUtil.MESSAGE_LEN) {
					msg += " 文件不能超过" + IMUtil.MESSAGE_LEN_M + "M,当前文件" + fb.length / IMUtil.MESSAGE_LEN_1M + " M !!!";
				} else {
					Message message = IMUtil.buildMessageObject(MessageType.FILE_REQ, fb);
					message.addOptions(IMUtil.SENDER, IMClientContext.get().getCurrentUser().getUserid());
					message.addOptions(IMUtil.RECEIVER, otherUser.getUserid());
					message.addOptions("fileName", file.getName());
					IMClientContext.get().sendMessage(message);
				}
				// 信息回显
				msg = "发送文件\n  " + msg + "";
				msg = IMUtil.formatMessage(IMClientContext.get().getCurrentUser().getUsername(), msg);
				IMClientContext.get().addMessage(otherUser.getUserid(), msg, false);
				refreshMessage();
				taMsg.setText("");// 清空
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (!StringUtil.isNullOrEmpty(msg)) {
			msg = IMUtil.formatMessage(IMClientContext.get().getCurrentUser().getUsername(), msg);
			// 给对方发送消息
			IMClientContext.get().sendMessage(otherUser, msg);
			// 格式化消息并添加到对方消息队列中，但是显示的名称是当前用户，用户回显信息
			IMClientContext.get().addMessage(otherUser.getUserid(), msg, false);
			// otherUser.setMsgCount(otherUser.getMsgCount() + 1);
			// 刷新消息列表
			refreshMessage();
			taMsg.setText("");// 清空
		}
	}

	// 刷新用户信息
	public void refreshUser(User user) {
		this.otherUser = user;
		SwingUtilities.invokeLater(() -> {
			lbUsername.setText(user.getUsername());
			setTitle(user.getUsername());
			if (user.getSex() == 0) {
				lbImage.setIcon(IMClientContext.woman);
			} else {
				lbImage.setIcon(IMClientContext.man);
			}
		});
	}

	// 刷新消息列表
	public ChatDialog refreshMessage() {
		SwingUtilities.invokeLater(() -> {
			Queue<String> msgList = IMClientContext.get().getMessage(otherUser.getUserid());
			String text = "";
			if (null != msgList) {
				text = msgList.stream().collect(Collectors.joining("\r\n"));
			}
			// 设置显示文本
			taMsgList.setText(text);
			// 滚动滚动条
			scrollBarMsg.setValue(scrollBarMsg.getMaximum());
		});
		return this;
	}

}
